package tm.testing;


import java.util.ArrayList;
import java.util.Iterator;

import com.jme.bounding.BoundingBox;
import com.jme.curve.Curve;
import com.jme.curve.CurveController;
import com.jme.entity.Entity;
import com.jme.scene.Spatial;

public class Vehicle extends Entity {

	public static final int IDLE		= 0;
	public static final int DRIVING 	= 1;
	
	protected int motionState;
	protected CurveController cc;
	protected float acceleration;
	protected float maxSpeed;
	protected Curve curve;
	
	public Vehicle(String id, Curve curve, Spatial s) {
		super("VEHICLE_"+id);
		//Load this out dynamically? and load the model in-class? would be nice uhm?
		acceleration = 0.001f;
		maxSpeed = 0.1f;
		this.curve = curve;
		setMotionState(IDLE);
		s.setName(id);
		s.setModelBound(new BoundingBox());
		s.updateModelBound();
		setSpatial(s);
		initMotionController();
	}
	
	public int getMotionState() {
		return motionState;
	}
	
	public void setMotionState(int state) {
		motionState = state;
	}
	
	protected void initMotionController() {
		cc = new CurveController(curve, getSpatial());
		getSpatial().addController(cc);
		cc.setSpeed(0);
		cc.setRepeatType(CurveController.RT_CYCLE);
		cc.setAutoRotation(true);
		cc.setOrientationPrecision(0.01f);
	}
	
	public void update() {
		switch(motionState) {
		case IDLE:
			cc.setSpeed(0);
			break;
		case DRIVING:
			if(cc.getSpeed()<maxSpeed) {
				cc.setSpeed(cc.getSpeed()+acceleration+(cc.getSpeed()*0.05f));
			}
			break;
		}	
	}
	/**
	 * 
	 * @param vehicleList The global list of attached vehicles
	 * @param spatialName The name of the spatial which vehicle is to be searched
	 * @return  Returns a reference to the vehicle which contains the Spatial with the given name. Returns
	 * 			null if there is no vehicle found.
	 */
	public static Vehicle getVehicleBySpatialName(ArrayList<Vehicle> vehicleList, String spatialName) {
		Iterator<Vehicle> itr = vehicleList.iterator();
		while(itr.hasNext()) {
			Vehicle tmp = itr.next();
			if(tmp.getSpatial().getName().equals(spatialName)) {
				//Return the vehicle if the Spatial name matches the specified one
				return tmp;
			}
		}
		//Return null if no vehicle is found
		return null;
	}
	
}
